package com.yunmai.web.common.sms;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.yunmai.framework.spring.context.ApplicationContextProvider;
import com.yunmai.web.common.redis.RedisCacheManager;
import com.yunmai.web.exception.BusinessResponseException;
import com.yunmai.web.exception.error.ErrorMessageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author WangChen
 * @since 2021-03-12 09:43
 **/
@Service
public class SmsCacheService {

    private static final Logger logger = LoggerFactory.getLogger(SmsCacheService.class);

    @Autowired
    private RedisCacheManager redisCacheManager;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ApplicationContextProvider applicationContextProvider;

    /**
     * 测试环境
     */
    private static final String TEST_ENVIRONMENT = "test";
    private static final String DEFAULT_CODE = "000000";

    private static final String PREFIX = "sms:";

    /**
     * 验证默认有效期
     */
    private static final int DEFAULT_EXPIRE = 5;
    private static final int CODE_MAX_LENGTH = 6;


    /**
     * 发送短信验证码
     *
     * @param phone
     * @return boolean
     */
    public boolean send(String phone) {
        try {
            String randomCode;
            //测试环境
//            if (StrUtil.equals(TEST_ENVIRONMENT, applicationContextProvider.getActive())) {
//                randomCode = DEFAULT_CODE;
//            } else {
//
//            }
            randomCode = RandomUtil.randomNumbers(CODE_MAX_LENGTH);
            if (!smsService.send(phone, randomCode, DEFAULT_EXPIRE)) {
                throw new BusinessResponseException(ErrorMessageResponse.SEND_SMS_FAIL.convert());
            }
            redisCacheManager.put(getKey(phone, randomCode), "success", DEFAULT_EXPIRE, TimeUnit.MINUTES);
            return true;
        } catch (Exception ex) {
            logger.info("[SmsCacheService] error: {}", ExceptionUtil.stacktraceToString(ex));
            throw new BusinessResponseException(ErrorMessageResponse.SEND_SMS_FAIL.convert());
        }

    }

    /**
     * 校验验证码是否正确
     *
     * @param phone 手机号
     * @param code  随机code
     * @return boolean
     */
    public void verify(String phone, String code) {
        if (ObjectUtil.isNotEmpty(redisCacheManager.getValue(getKey(phone, code)))) {
            logger.info("[SmsCacheService] verify success phone = {}, code = {}", phone, code);
            //redisCacheManager.delete(getKey(phone, code));
            return;
        }
        throw new BusinessResponseException(ErrorMessageResponse.VERIFY_SMS_FAIL.convert());
    }


    private String getKey(String phone, String code) {
        return PREFIX + phone + "-" + code;
    }
}
